# @Time : 2021/4/7 17:02
# @Author : Fioman 
# @Phone : 13149920693
"""
主要用来存放数据中常用的一些工具函数,这些函数会被不同的模块调用
"""
from PIL import Image
from io import BytesIO
import base64
import ctypes
import inspect
import time


def get_time_now_string():
    """
    获取当前时间的时间格式字符串, "%Y-%m-%d %H-%M-%S" 格式字符串
    :return: 返回2021-04-08 17-23-46 这样的时间字符串
    """
    return time.strftime("%Y-%m-%d--%H-%M-%S", time.localtime())


def get_time_now_string_for_web():
    """
    获取当前时间的时间格式字符串,"%Y-%m-%d %H:%M:%S"格式,前端显示用
    :return:
    """
    return time.strftime("%Y-%m-%d %H:%M:%S")


def image_to_string(image):
    """
    将一幅图转换成字符串的格式,可以发送给前端的那种字符串类型
    :param image:要转换的图片,可以是彩色的,也可以是灰度图
    :return: 返回图像的字符串格式,可以让前端进行显示
    """
    clone = image.copy()
    pilImg = Image.fromarray(clone)
    buffer = BytesIO()
    pilImg.save(buffer, format="JPEG")
    imageStr = base64.b64encode(buffer.getvalue()).decode('utf-8')
    return imageStr


def async_raise(tid, exctype):
    """
    raises the exception,performs cleanup if needed
    :param tid:线程id
    :param exctype:线程的类型
    :return:
    """
    tid = ctypes.c_long(tid)
    if not inspect.isclass(exctype):
        exctype = type(exctype)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        # """if it returns a number greater than one, you're in trouble,
        # and you should call it again with exc=NULL to revert the effect"""
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
        raise SystemError("PyThreadState_SetAsyncExc failed")


def stop_thread(thread):
    """
    停止线程
    :param thread:
    :return:
    """
    async_raise(thread.ident, SystemExit)
